package com.samsung.utils.phone.helpers;

import java.io.File;
import java.io.IOException;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPListParseException;

public class FTP4Api {

	FTPDataTransferListener ftpListener;
	public long downloded = 0;
	public long fileSize = -1;
	public File fileSaveLocation = null;
	private FTPClient client;

	public FTP4Api(FTPDataTransferListener ftpListener) {

		this.ftpListener = ftpListener;
	}

	public void discard() {

		try {
			if (client != null) {
				client.abortCurrentDataTransfer(true);
				client.wait();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPIllegalReplyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void download(String serverAddress, String userName,
			String userPass, String[] serverFileDirectory, String file)
			throws IllegalStateException, IOException,
			FTPIllegalReplyException, FTPException, FTPDataTransferException,
			FTPAbortedException, FTPListParseException {

		downloded = 0;
		fileSize = -1;
		client = new FTPClient();
		// LogUtils.la("client.getAutoNoopTimeout()"+client.getAutoNoopTimeout());
		// client.setAutoNoopTimeout(1000);
		// LogUtils.la("client.getAutoNoopTimeout()"+client.getAutoNoopTimeout());
		// client.setPassive(false); // Active mode
		// System.setProperty("ftp4j.activeDataTransfer.acceptTimeout", "1000");
		client.connect(serverAddress);
		client.login(userName, userPass);

		for (int i = 0; i < serverFileDirectory.length; i++) {
			client.changeDirectory(serverFileDirectory[i]);
		}
		FTPFile[] list = client.list();
		for (FTPFile fileFtp : list) {
			if (fileFtp.getName().equals(file)) {
				fileSize = fileFtp.getSize();
			}
		}
		try {
			if (fileSize > 0) {
				client.download(file, fileSaveLocation, ftpListener);
			}
		} catch (Exception e) {
		}
		client.disconnect(true);
	}
}
